import Vue from 'vue'
import VueRouter from 'vue-router'
import notFound from "@/views/404.vue"
import Main from "@/views/main.vue"
import { getStorageUserInfo } from '@/utils'
Vue.use(VueRouter)

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
    if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
    return originalPush.call(this, location).catch(err => err)
}
const publicRoutes = ['/login', '/couponLink']
const routes = [
    {
        path: '/',
        name: 'home',
        component: () => import('../views/home.vue'),
        meta: { permissions: [], title: '主页' },
    },

    {
        path: '/login',
        name: 'login',
        component: () => import('../views/login.vue'),
    },
    {
        path: '/couponLink',
        name: 'couponLink',
        component: () => import('../views/couponLink.vue'),
    },
    {
        path: '/activityLink',
        name: 'activityLink',
        component: () => import('../views/activityLink.vue'),
    },
    {
        path: '/test',
        name: 'test',
        component: () => import('../views/test.vue'),
    },
    {
        path: '/404',
        name: 'Page404',
        component: notFound
    },
    {
        path: '/largeScreen',
        name: 'largeScreen',
        component: () => import('../views/largeScreen/index.vue'),
        icon: '\ue670',
        meta: { permissions: [], title: '数据大屏' },
    },
    {
        path: '/agencyLarge',
        name: 'agencyLarge',
        component: () => import('../views/largeScreenAgency/index.vue'),
        icon: '\ue670',
        meta: { permissions: [], title: '数据大屏' },
    },
    {
        path: '*',
        redirect: '/404'
    }
]
export const platformRoute = {
    path: '/platform',
    name: 'platform',
    component: () => import('../views/platform/index.vue'),
    meta: { permissions: [], title: '平台管理' },
    children: [
        {
            path: '/platformAgency',
            name: 'platformAgency',
            component: Main,
            icon: '\ue741',
            meta: { mustPers: ['marketAdmin'], permissions: ['organizationManage'], title: '机构管理' },
            children: [
                {
                    path: '/platform/platformAgency',
                    name: 'platformAgency',
                    component: () => import('../views/platform/agency/index.vue'),
                    meta: { permissions: [], title: '机构列表' },
                }
            ],
        },
        {
            path: '/platformMyAgency',
            name: 'platformMyAgency',
            component: Main,
            icon: '\ue741',
            meta: { mustPers: ['marketShop'], permissions: [], title: '我的机构' },
            children: [
                {
                    path: '/platform/myAgency',
                    name: 'platformMyAgency',
                    component: () => import('../views/platform/agency/myAgency.vue'),
                    meta: { permissions: [], title: '我的机构' },
                }
            ],
        },
        {
            path: '/platformDoctor',
            name: 'platformDoctor',
            component: Main,
            icon: '\ue741',
            meta: { permissions: ['doctorManage'], title: '医生管理' },
            children: [
                {
                    path: '/platform/doctor',
                    name: 'platformDoctorIndex',
                    component: () => import('../views/platform/doctor/index.vue'),
                    meta: { permissions: [], title: '医生管理' },
                }
            ],
        },
        {
            path: '/platformPatient',
            name: 'platformPatient',
            component: Main,
            icon: '\ue741',
            meta: { permissions: ['patientManage'], title: '患者管理' },
            children: [
                {
                    path: '/platform/patient',
                    name: 'platformPatientIndex',
                    component: () => import('../views/platform/patient/index.vue'),
                    meta: { permissions: [], title: '患者管理' },
                }
            ],
        },
        {
            path: '/platformUser',
            name: 'platformUser',
            component: Main,
            icon: '\ue741',
            meta: { permissions: [], title: '员工管理' },
            children: [
                {
                    path: '/platform/staffMgt',
                    name: 'platformStaffMgt',
                    component: () => import('../views/platform/staffMgt/index.vue'),
                    meta: { permissions: ['accountManage'], title: '人员管理' },
                },
                {
                    path: '/platform/permissionMgt',
                    name: 'platformPermissionMgt',
                    component: () => import('../views/platform/permissionMgt/index.vue'),
                    meta: { permissions: ['permissionManage'], title: '权限管理' },
                },
            ],
        },
        {
            path: '/platformPoint',
            name: 'platformPoint',
            component: Main,
            icon: '\ue741',
            meta: { mustPers: ['marketAdmin'], permissions: ['integralConfigManage'], title: '积分管理' },
            children: [
                {
                    path: '/platform/pointsSetting',
                    name: 'platformPointsSetting',
                    component: () => import('../views/platform/points/pointsSetting.vue'),
                    meta: { permissions: ['integralConfig'], title: '积分设置' },
                },
                {
                    path: '/platform/pointsUser',
                    name: 'platformPointsUser',
                    component: () => import('../views/platform/points/user.vue'),
                    meta: { permissions: ['userIntegral'], title: '用户积分' },
                },
            ],
        },
        {
            path: '/platformSys',
            name: 'platformSys',
            component: Main,
            icon: '\ue741',
            meta: { mustPers: ['marketAdmin'], permissions: ['systemManage'], title: '系统管理' },
            children: [
                {
                    path: '/platform/department',
                    name: 'platformDepartment',
                    component: () => import('../views/platform/system/department/index.vue'),
                    meta: { permissions: ['officeInfoManage'], title: '科室信息管理' },
                },
                {
                    path: '/platform/disease',
                    name: 'platformDisease',
                    component: () => import('../views/platform/system/disease/index.vue'),
                    meta: { permissions: ['illnessInfoManage'], title: '疾病信息管理' },
                },

                // {
                //     path: '/platform/sysSeting',
                //     name: 'platformSysSeting',
                //     component: () => import('../views/platform/system/sysSeting.vue'),
                //     meta: { permissions: [], title: '系统设置' },
                // },
            ],
        },
        {
            path: '/dataSys',
            name: 'dataSys',
            component: Main,
            icon: '\ue741',
            meta: { mustPers: ['marketAdmin'], permissions: [], title: '数据统计' },
            children: [
                {
                    path: '/platform/seeDoctor',
                    name: 'platformSeeDoctor',
                    component: () => import('../views/platform/dataSys/seeDoctor.vue'),
                    meta: { permissions: [], title: '就诊分析' },
                },
                {
                    path: '/platform/consumption',
                    name: 'platformConsumption',
                    component: () => import('../views/platform/dataSys/consumption.vue'),
                    meta: { permissions: [], title: '消费分析' },
                }
            ],
        },

    ],
}
export const shopMallRoute = {
    path: '/shopMall',
    name: 'shopMall',
    component: () => import('../views/shopMall/index.vue'),
    meta: { permissions: [], title: '商城管理' },
    children: [
        {
            path: '/shopMallGoods',
            name: 'shopMallGoods',
            component: Main,
            icon: '\ue741',
            meta: { permissions: ['goodsManage'], title: '商品管理' },
            children: [
                {
                    path: '/shopMall/goodsList',
                    name: 'shopMallGoodsList',
                    component: () => import('../views/shopMall/goods/goodsList.vue'),
                    meta: { mustPers: ['marketShop'], permissions: [], title: '商品列表' },
                },
                {
                    path: '/shopMall/goodsAuth',
                    name: 'shopMallGoodsAuth',
                    component: () => import('../views/shopMall/goods/goodsAuth.vue'),
                    meta: { mustPers: ['marketAdmin'], permissions: ['goodsAudit'], title: '商品审核' },
                },
            ],
        },
        {
            path: '/shopMallOrder',
            name: 'shopMallOrder',
            component: Main,
            icon: '\ue741',
            meta: { permissions: ['orderManage'], title: '订单管理' },
            children: [
                {
                    path: '/shopMall/orderList',
                    name: 'shopMallOrderList',
                    component: () => import('../views/shopMall/order/orderList.vue'),
                    meta: { permissions: ['orderManage'], title: '订单列表' },
                },
            ],
        },
        {
            path: '/shopMallCategory',
            name: 'shopMallCategory',
            component: Main,
            icon: '\ue741',
            meta: { mustPers: ['marketAdmin'],permissions: ['goodsClassifyManage'], title: '分类管理' },
            children: [
                {
                    path: '/shopMall/category',
                    name: 'shopMallCategory',
                    component: () => import('../views/shopMall/system/category/category.vue'),
                    meta: { permissions: [], title: '一级分类' },
                },
                {
                    path: '/shopMall/categoryNext',
                    name: 'shopMallCategoryNext',
                    component: () => import('../views/shopMall/system/category/categoryNext.vue'),
                    meta: { permissions: [], title: '二级分类' },
                },
            ],
        },
        {
            path: '/shopMallSys',
            name: 'shopMallSys',
            component: Main,
            icon: '\ue741',
            meta: { mustPers: ['marketAdmin'],permissions: ['storeConfig'], title: '商城配置' },
            children: [
                {
                    path: '/shopMall/banner',
                    name: 'shopMallBanner',
                    component: () => import('../views/shopMall/system/banner/index.vue'),
                    meta: { permissions: ['bannerManage'], title: 'banner管理' },
                },
                {
                    path: '/shopMall/hotWord',
                    name: 'shopMallHotWord',
                    component: () => import('../views/shopMall/system/hotWord/index.vue'),
                    meta: { permissions: ['hotWordManage'], title: '热词管理' },
                },

            ],
        },

    ],
}
export const marketRoute = {
    path: '/market',
    name: 'market',
    component: () => import('../views/market/index.vue'),
    meta: { permissions: [], title: '营销中心' },
    children: [
        {
            path: '/platActivity',
            name: 'platActivity',
            component: Main,
            icon: '\ue741',
            meta: { permissions: ['activityManage'], title: '活动中心' },
            children: [
                {
                    path: '/market/platActivityList',
                    name: 'marketPlatActivityList',
                    component: () => import('../views/market/platActivity/list.vue'),
                    meta: { permissions: [], title: '活动中心' },
                },
            ],
        },
        {
            path: '/platCoupon',
            name: 'platCoupon',
            component: Main,
            icon: '\ue741',
            meta: { mustPers: ['marketAdmin'],permissions: ['couponManage'], title: '平台优惠券中心' },
            children: [
                {
                    path: '/market/generalCouponPlat',
                    name: 'marketGeneralCouponPlat',
                    component: () => import('../views/market/platCoupon/generalCoupon.vue'),
                    meta: { permissions: [], title: '通用券' },
                },
                {
                    path: '/market/shopMallCouponPlat',
                    name: 'marketShopMallCouponPlat',
                    component: () => import('../views/market/platCoupon/shopMallCoupon.vue'),
                    meta: { permissions: [], title: '商城券' },
                },
                {
                    path: '/market/exclusiveCouponPlat',
                    name: 'marketExclusiveCouponPlat',
                    component: () => import('../views/market/platCoupon/exclusiveCoupon.vue'),
                    meta: { permissions: [], title: '专属券' },
                },
            ],
        },
        {
            path: '/coupon',
            name: 'coupon',
            component: Main,
            icon: '\ue741',
            meta: { mustPers: ['marketShop'],permissions: ['organCouponManage'], title: '优惠券中心' },
            children: [
                {
                    path: '/market/generalCoupon',
                    name: 'marketGeneralCoupon',
                    component: () => import('../views/market/coupon/generalCoupon.vue'),
                    meta: { permissions: [], title: '通用券' },
                },
                {
                    path: '/market/shopMallCoupon',
                    name: 'marketShopMallCoupon',
                    component: () => import('../views/market/coupon/shopMallCoupon.vue'),
                    meta: { permissions: [], title: '商城券' },
                },
                {
                    path: '/market/exclusiveCoupon',
                    name: 'marketExclusiveCoupon',
                    component: () => import('../views/market/coupon/exclusiveCoupon.vue'),
                    meta: { permissions: [], title: '专属券' },
                },
            ],
        },
        {
            path: '/reconciliation',
            name: 'reconciliation',
            component: Main,
            icon: '\ue741',
            meta: { permissions: ['backupManage'], title: '核销对账' },
            children: [
                {
                    path: '/market/reconciliation',
                    name: 'marketReconciliation',
                    component: () => import('../views/market/reconciliation/index.vue'),
                    meta: { permissions: [], title: '核销对账' },
                },
            ],
        }

    ]
}
export const operatorRoutes = [
    platformRoute,
    shopMallRoute,
    marketRoute
]

const router = new VueRouter({
    mode: 'hash',
    base: process.env.BASE_URL,
    routes: routes
})

router.beforeEach((to, from, next) => {
    let userInfo = getStorageUserInfo()

    if (userInfo && userInfo.id) {
        //已登录
        next()
    } else if (publicRoutes.indexOf(to.path) !== -1) {
        //公开路由
        next()
    } else {
        //
        next('/login')
    }

});

router.afterEach(route => {
    //
});
export const setRouter = (callback) => {
    const list = generateRoutes()
    for (let r of list) {
        router.addRoute(r)
    }
    callback && callback()
}
const hasPermission = (permissions, route) => {
    if (route.meta && route.meta.mustPers && route.meta.mustPers.length > 0) {
        //mustPers中的权限必须全部满足
        let tab = true
        route.meta.mustPers.forEach((item) => {
            const one = permissions.find((allOne) => {
                return allOne === item
            })
            if (!one) tab = false
        })
        if (!tab) return false
    }

    if (route.meta && route.meta.permissions && route.meta.permissions.length > 0) {
        //满足权限其中一个就可用
        return permissions.some(permission => route.meta.permissions.includes(permission))
    } else {
        return true
    }
}
const filterAsyncRoutesWithPermissions = (routes, permissions) => {
    const res = []
    routes.forEach(route => {
        const r = { ...route }
        if (hasPermission(permissions, r)) {

            if (r.children && r.children.length > 0) {
                r.children = filterAsyncRoutesWithPermissions(r.children, permissions)
                if (r.children.length > 0) res.push(r)
            } else {
                res.push(r)
            }

        }
    })
    return res
}
export const generateRoutes = (routes) => {
    let validRoutes = []

    if (routes) {
        validRoutes = routes
    } else {
        validRoutes = operatorRoutes
    }
    const userInfo = getStorageUserInfo()
    if (userInfo && userInfo.id) {
        const userPermissions = userInfo.permissions

        let permissions = []
        if (userInfo.type === "PLATFORM") {
            permissions = ['marketAdmin'].concat(userPermissions)
        } else {
            permissions = ['marketShop'].concat(userPermissions)
        }
        return filterAsyncRoutesWithPermissions(validRoutes, permissions)

    }


    return []
}
export default router
